﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using TCommon;

namespace WebTest
{
    public partial class ChatControl : UserControl
    {
        private bool keydowncalled = false;

        private string lastUserId = "";
        private string lastChatTime;
        private string lastToUser = "";
        private bool isFirstRow = true;
        private const string PlaceHolderText = "输入聊天内容，按Enter键发送...";

        private static string[] urlEndStrings = new[]
            {"com", "cn", ".net", "cc", "org", "vip", "xin", "top", "club", "xyz", "wang", "win"}; 

        public ChatControl()
        {
            InitializeComponent();
            ChatHistory.DocumentText = @"<html><head><style>span:hover{text-decoration:overline}</style></head><body></body></html>";
            ChatInput.GotFocus += ChatInput_GotFocus;
            ChatInput.LostFocus += ChatInput_LostFocus;
            if (string.IsNullOrWhiteSpace(ChatInput.Text))
                ChatInput.Text = PlaceHolderText;
                ChatInput.ForeColor = Color.Gray;
        }

        public void SetToUsers(List<string> users) {
            users.Insert(0, "所有人");
            users.Remove(TCommon.AppContext.CurrentUser);
            this.comboBoxTo.DataSource = users;
        }

        private void ChatInput_LostFocus(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ChatInput.Text))
                ChatInput.Text = PlaceHolderText;
                ChatInput.ForeColor = Color.Gray;
        }

        private void ChatInput_GotFocus(object sender, EventArgs e)
        {
            if (ChatInput.Text == PlaceHolderText)
            {
                ChatInput.Text = "";
                ChatInput.ForeColor = Color.FromArgb(255, 136, 68, 103);
            }
           
        }

        private void ShowMessage(string message, string fromUser, string toUser) {
            var body = ChatHistory.Document.GetElementsByTagName("body")[0];
            var element = ChatHistory.Document.CreateElement("div");
            var text = WebUtility.HtmlEncode(message);
            text = text.Replace("\n", "<br>");

            Uri uriResult;
            bool isUrl = ValidHttpURL(text.Trim(), out uriResult);
            string href = text;
            if (isUrl)
            {
                if (!text.Trim().StartsWith("http"))
                {
                    href = $"http://{text}";
                }
                else
                {
                    href = text;
                }

                text = $"<a href='{href}' target='_blank'>{text}</a>";
            }

            string userId = fromUser;
            var currentTime = DateTime.Now;
            var time = currentTime.ToString("hh:mm tt");

            string fromGuid = "";
            string toGuid = "";
            if (lastUserId != userId || time != lastChatTime || toUser != lastToUser)
            {
                string br = "<div style='margin-top:8px'>";
                if (isFirstRow)
                {
                    br = "";
                    isFirstRow = false;
                }

                string fromSpan = "";
                if (userId != "我")
                {
                    fromGuid = Guid.NewGuid().ToString();
                    fromSpan = $"<span id='{fromGuid}' style='color:blue;cursor:pointer'>{userId}</span>";
                }
                else
                {
                    fromSpan = userId;
                }

                string toSpan = "";
                if (toUser != "我")
                {
                    toGuid = Guid.NewGuid().ToString();
                    toSpan = $"<span id='{toGuid}' style='color:blue;cursor:pointer'>{toUser}</span>";
                }
                else {
                    toSpan = toUser;
                }

                string privateSpan = "";
                if (toUser != "所有人") {
                    privateSpan = "<span style='color:#EB6464'> (私聊)</span>";
                }

                element.InnerHtml = $"{br}<div style='float:right;color:#A5749D;font-size:12px;font-family:Microsoft YaHei;'>{time}</div><div style='font-size:13px;font-family:Microsoft YaHei;color:#747487'>" +
                    $"{fromSpan}对{toSpan}说:{privateSpan}</div>" +
                    $"<div style='font-size:13px;font-family:Microsoft YaHei;color:#884444;margin-bottom:4px;word-wrap:break-word;word-break:break-all;'>{text}</div>";
                lastUserId = userId;
                lastChatTime = time;
                lastToUser = toUser;
            }
            else
            {
                element.InnerHtml = $"<div style='font-size:13px;font-family:Microsoft YaHei;color:#884444;margin-bottom:4px;word-wrap:break-word;word-break:break-all;'>{text}</div>";
            }
            body?.AppendChild(element);

            if (!string.IsNullOrEmpty(toGuid)) {
                var toUserElement = ChatHistory.Document.GetElementById(toGuid);
                toUserElement.Click += ToUserElement_Click;
            }

            if (!string.IsNullOrEmpty(fromGuid)) {
                var fromUserElement = ChatHistory.Document.GetElementById(fromGuid);
                fromUserElement.Click += FromUserElement_Click;
            }
        }

        private void FromUserElement_Click(object sender, HtmlElementEventArgs e)
        {
            if (sender is HtmlElement ele)
            {
                comboBoxTo.SelectedItem = ele.InnerText;
            }
        }

        private void ToUserElement_Click(object sender, HtmlElementEventArgs e)
        {
            if (sender is HtmlElement ele) {
                comboBoxTo.SelectedItem = ele.InnerText;
            }
        }

        private void ChatInput_KeyDown(object sender, KeyEventArgs e)
        {
            keydowncalled = false;

            if (e.KeyCode == Keys.Enter && !e.Control)
            {
                //inputMsg = string.Format("{0}\"roomid\":{1},\"cmd\":9,\"userid\":{2}, \"txt\":{3}{4}","{", TRTC.VideoMainForm.roomId1, comboBoxTo.Text, ChatInput.Text, "}");
                //fasongmessage(inputMsg);
                keydowncalled = true;
                var toUser = comboBoxTo.Text;
                ShowMessage(ChatInput.Text, "我", toUser);

                ChatInput.Text = string.Empty;
                e.Handled = true;
                ChatHistory.Document.Window.ScrollTo(0, ChatHistory.Document.Body.ScrollRectangle.Height);
            }
            
        }
        //public void fasongmessage(string msg)
        //{
        //    try
        //    {
        //        if (string.IsNullOrEmpty(msg))
        //            System.Windows.MessageBox.Show("空值不让传！");
        //        TRTC.VideoMainForm.client.SendMessage(msg);
        //    }
        //    catch (Exception ex)
        //    {
        //        System.Windows.MessageBox.Show(ex.Message);
        //    }
        //}
        private void ChatInput_KeyPress(object sender, KeyPressEventArgs e)
        {
            if(keydowncalled)
                e.Handled = true;
        }

        public static bool ValidHttpURL(string s, out Uri resultURI)
        {
            if (!Regex.IsMatch(s, @"^https?:\/\/", RegexOptions.IgnoreCase))
                s = "http://" + s;

            var array = s.Split('.');
            if (Uri.TryCreate(s, UriKind.Absolute, out resultURI) && array.Length > 1 && urlEndStrings.Contains(array[array.Length - 1]))
            {
                return (resultURI.Scheme == Uri.UriSchemeHttp ||
                        resultURI.Scheme == Uri.UriSchemeHttps);
            }    

            return false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ShowMessage(ChatInput.Text, "小明", "我");

            ChatInput.Text = string.Empty;
            ChatHistory.Document.Window.ScrollTo(0, ChatHistory.Document.Body.ScrollRectangle.Height);
        }
    }
}
